package cn.linran._02_asynchronous;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class Consumer {
    public static void main(String[] args) throws Exception {
        //1.0创建消费者对象，指定组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("asyn_group");
        //1.1设置NameServer
        consumer.setNamesrvAddr("localhost:9876");
        //1.2设置消费者消费主题topic，二级分类可以为*，也可以指定
        consumer.subscribe("asyn_topic","*");
        //1.3注册回调实现类来处理从broker拉取回来的信息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                //1.4打印得到的信息
                for(MessageExt msg:list){
                    String result = new String(msg.getBody(), StandardCharsets.UTF_8);
                    System.out.println(result);
                }
                //1.5标记该消息已经被消费成功
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //1.6启动消费者
        consumer.start();
        System.out.println("Consumer启动成功");
    }
}
